<template>
    <div class="manage"> 
        <HeadBar />

        <div class="table container">
            <div class="add">
                <el-button type="primary" @click="add()">添加</el-button>
            </div>

            <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="title" label="标题" />
                <el-table-column prop="fileName" label="文件名"  width="300"/>
                <el-table-column prop="type" label="模型" width="100">
                    <template #default="scope">
                        <span v-if="scope.row.type === 1">通义千问</span>
                        <span v-else-if="scope.row.type === 2">deepseek</span>
                    </template>
                </el-table-column>
                <el-table-column prop="time" label="创建时间" width="200">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button size="small" type="success" @click="interact(scope.row)">对话</el-button>
                        <el-button size="small" type="primary" @click="update(scope.row)">修改</el-button>
                        <el-button size="small" type="danger" @click="del(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog v-model="dialogVisible" title="添加模型" width="50%">
            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
                <el-form-item label="标题：">
                    <el-input v-model="form.title" autocomplete="off" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="模型：" @change="changeModel">
                    <el-select v-model="form.type" placeholder="请选择模型">
                        <el-option label="通义千问" :value="1"></el-option>
                        <el-option label="deepseek" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文件：" v-if="form.type == 1">
                    <el-upload
                        class="upload-demo"
                        accept=".pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .txt"
                        action
                        :show-file-list="false"
                        :multiple="false"
                        :before-upload="beforeUpload"
                        :http-request="handleUpload">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                    <p>{{ form.fileName }}</p>
                </el-form-item>
                <el-form-item label="提示词：">
                    <el-input 
                        v-model="form.prompt" 
                        autocomplete="off" 
                        placeholder="请输入提示词" 
                        :rows="20"
                        type="textarea">
                    </el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirm()">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import HeadBar from '@/layout/HeadBar/index.vue'
import { nextTick, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { customList, customAdd, customUpdate, customDelete } from '@/api/custom.js'
import { upload } from '@/api/fls.js'
import { parseTime } from '@/utils/index.js'
import { useChattingStore } from '@/stores'

const store = useChattingStore()

const router = useRouter()
const tableData = ref([])

const getList = async () => {
    const res = await customList()
    console.log(res.list)
    tableData.value = res.list
}

getList()    // 初始化数据

const interact = (row) => {
    store.connetChat(row)
    router.push({
        path: '/main/chat',
    })
}

const changeModel = () => {
    if(form.value.type != 1) {
        form.value.fileId = ''
        form.value.fileName = ''
    }
}

const ruleForm = ref()
const dialogVisible = ref(false)
const dialogStatus = ref("add") // add | update
const form = ref({
    title: '',
    fileName: '',
    fileId: '',
    prompt: '',
    type: null,
    id: undefined
})
const rules = ref({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' }
    ],
    prompt: [
        { required: false, message: '请输入提示词', trigger: 'blur' }
    ],
})

const beforeUpload = (file) => {          // 文件上传前限制
    const isAllowFileType = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'md'].includes(file.name.split('.').pop().toLowerCase())
    if (!isAllowFileType) {
        ElMessage.error('请上传pdf、doc、docx、xls、xlsx、ppt、pptx、txt、md格式的文件！')
        return false
    }
    return isAllowFileType;
}
const handleUpload = (res) => {
    form.value.fileName = res.file.name
    let fd = new FormData()
    fd.append('type', 1);
    fd.append('file', res.file);
    upload(fd).then(data => {
        form.value.fileId = data.fileId
    })
}

const add = () => {
    form.value = {
        title: '',
        prompt: '',
        fileId: '',
        fileName: '',
        type: null,
        id: undefined
    }
    dialogStatus.value = 'add'
    dialogVisible.value = true
    nextTick(() => {
        ruleForm.value.clearValidate()
    })
}

const update = (row) => {
    form.value = {
        title: row.title,
        prompt: row.prompt,
        fileId: row.fileId,
        fileName: row.fileName,
        type: row.type,
        id: row.id
    }
    dialogStatus.value = 'update'
    dialogVisible.value = true
    nextTick(() => {
        ruleForm.value.clearValidate()
    })
}

const confirm = async () => {
    if (dialogStatus.value === 'add') {
        await customAdd(form.value)
        ElMessage({
            message: '添加成功',
            type: 'success',
        })
        dialogVisible.value = false
        getList()
    } else if (dialogStatus.value === 'update') {
        await customUpdate(form.value)
        ElMessage({
            message: '修改成功',
            type: 'success',
        })
        dialogVisible.value = false
        getList()
    }
}

const del = async (row) => {
    await customDelete({id: row.id})
    ElMessage({
        message: '删除成功',
        type: 'success',
    })
    getList()
}

</script>

<style lang="scss" scoped>
.manage {
    height: 100%;
    .table {
        width: 100%;
        height: calc(100% - #{$headHeight});
        overflow-y: auto;
        padding: 10px;
        .add {
            text-align: right;
            margin-bottom: 20px;
        }
    }
}
</style>